iT邦幫忙

0

Django #4 專案:新增APP

joor 2022-07-24 12:31:361182 瀏覽
  • 分享至 

  • xImage
  •  

[目標]

建立api


1. 新增app

  • Syntax:
python manage.py startapp [appName]

新增user app 範例:
python manage.py startapp user

資料結構

system/            
    manage.py       
    system/
        __init__.py   
        settings.py #項目的設置/配置
        urls.py     #建置api
        asgi.py     
        wsgi.py    
#新增部分
   user/
      migrations/          #會自動創建  #紀錄DataBase Table結構操作紀錄
              __init__.py
      __init__.py 
      admin.py     #會自動創建  #後臺管理
      apps.py
      models.py    #會自動創建  #創建DataBase Table
      tests.py
      views.py     #接受 http(request)並返回 http(response)
      urls.py      #自己創建 ##建置api

2. Code 撰寫

https://ithelp.ithome.com.tw/upload/images/20220724/20137134KXtEe9EhG0.png

  • system/settings.py
#約在文件33行
INSTALLED_APPS = [
    'user.apps.UserConfig',
]
  • user/views.py

Request and response
接受 http(request)並返回 http(response)
https://ithelp.ithome.com.tw/upload/images/20220724/201371342D49ylq42p.png

from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json

# Create your views here.
@csrf_exempt
def login(request):
    if request.method == 'POST':
        body = json.loads(request.body)
        parameters = body['parameters']
        print(body)
        return HttpResponse(json.dumps(parameters))
    print(request.method)
    return HttpResponse('ok')
  • user/urls.py

須自己新增
API建置
https://ithelp.ithome.com.tw/upload/images/20220724/20137134ExIXsVyypF.png

from django.urls import path
from . import views

urlpatterns = [
    path('login', views.login),
]
  • system/urls.py

API建置
https://ithelp.ithome.com.tw/upload/images/20220724/20137134JA7sR2iQCA.png

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('user/', include('user.urls')),
]

3. 啟動測試

*Terminal

python manage.py runserver

http://127.0.0.1:8000/user/login

網頁會收到後端回應OK
後端會收到前端GET請求


上一篇
Angular前端API串接 :待PO文


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言